//
//  GYStoreAllViewController.m
//  GoodLuck
//
//  Created by apple on 2018/3/12.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

static NSString *storeAllHorCellIdentifier = @"storeAllHorCellIdentifier";
static NSString *storeAllVerCellIdentifier = @"storeAllVerCellIdentifier";
static NSString *storeAllHeadView = @"storeAllHeadView";
const NSInteger count = 20;

#import "GYStoreAllViewController.h"
#import "GYStoreAllHorCell.h"
#import "GYStoreAllVerCell.h"
#import "GYSearchGoos.h"
#import "GYNetWorkTools.h"
#import "GYSortView.h"
#import "GYSortSelectView.h"
#import "GYShopHomeViewController.h"
#import "GYNoAddressView.h"
#import "GYPriceScreenViewController.h"


@interface GYStoreAllViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

/** 选择排序方式界面 */
@property (nonatomic, weak) GYSortSelectView *selectView;

/** 排序视图 */
@property (nonatomic, strong) GYSortView *sortView;

/** 表示商品排列方式 */
@property (nonatomic, getter=isLayout) BOOL layout;

/** <#descrption#> */
@property (nonatomic, strong) UICollectionView *collectionView;

/** 数据源 */
@property (nonatomic, strong) NSMutableArray *goodsList;

//是否还有更多数据
@property (nonatomic, getter=isHasmore) BOOL hasmore;

/** 当前数据页数 */
@property (nonatomic, assign) NSInteger currentPage;

/** 记载当前数据的排布格式 */
@property (nonatomic, strong) NSString *key;

/** 数据顺序 */
@property (nonatomic, strong) NSString *order;

@end

@implementation GYStoreAllViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBColor(245, 245, 245);
    self.currentPage = 1;
    self.key = @"1";
    self.order = @"1";
    self.hasmore = YES;
    
    //初始化
    [self setupUI];
    
    //初始化视图
    [self setupCollectionView];
    
    //加载全部商品数据
    [self loadStoreAllGoods:[NSString stringWithFormat:@"%zd",self.currentPage] page:[NSString stringWithFormat:@"%zd",count] stc_id:@"" keyword:@"" key:@"1" order:@"1" price_from:@"" price_to:@""];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.selectView.frame = CGRectMake(0, 0, ScreenWidth, 50);
    self.collectionView.frame = CGRectMake(0, 50, ScreenWidth, self.view.height-50);
}
- (void)setupUI {
    //1.添加排序选择方式
    GYSortSelectView *selectView = [[[NSBundle mainBundle] loadNibNamed:@"GYSortSelectView" owner:nil options:nil] firstObject];
    selectView.selectorModeCallBack = ^(NSInteger tag,UIButton *btu,BOOL layout) {
        switch (tag) {
            case 1:
            {
                if (self.sortView != nil) {
                    self.sortView.hidden = !self.sortView.isHidden;
                }else {
                    self.sortView = [[[NSBundle mainBundle] loadNibNamed:@"GYSortView" owner:nil options:nil] firstObject];
                    self.sortView.frame = CGRectMake(0, 50, ScreenWidth, ScreenHeight-64-50);
                    [self.view addSubview:self.sortView];
                }
                __weak typeof(self) weakSelf = self;
                self.sortView.sortResultCallBack = ^(NSInteger tag,NSString *sortTitle) {
                    //1.隐藏视图
                    weakSelf.sortView.hidden = YES;
                    [btu setTitle:sortTitle forState:UIControlStateNormal];
                
                    //这里决定这个商品是怎么样排序的;
                    switch (tag) {
                        case 0:
                        {
                            weakSelf.key = @"1";
                            weakSelf.order  = @"2";
                        }
                            break;
                            
                        case 1:
                        {
                            weakSelf.key = @"2";
                            weakSelf.order  = @"2";
                        }
                            break;
                            
                        case 2:
                        {
                            weakSelf.key = @"2";
                            weakSelf.order  = @"2";
                        }
                            break;
                            
                        case 3:
                        {
                            weakSelf.key = @"4";
                            weakSelf.order  = @"2";
                        }
                            break;
                        default:
                            break;
                    }
                    
                    //清楚当前的页数的历史记录
                    weakSelf.currentPage = 1;
                    [weakSelf.goodsList removeAllObjects];
                    
                    //清楚记录是否数据的记录
                    weakSelf.hasmore = YES;
                    
                    //加载数据
                    [weakSelf loadStoreAllGoods:[NSString stringWithFormat:@"%zd",weakSelf.currentPage] page:[NSString stringWithFormat:@"%zd",count] stc_id:@"" keyword:@"" key:weakSelf.key order:weakSelf.order price_from:@"" price_to:@""];
                    

                };
                
            }
                break;
                
            case 2:
            {
                self.currentPage = 1;
                self.hasmore = YES;
                [self.goodsList removeAllObjects];
                self.key = @"3";
                self.order = @"2";
                
                [self loadStoreAllGoods:[NSString stringWithFormat:@"%zd",self.currentPage] page:[NSString stringWithFormat:@"%zd",count] stc_id:@"" keyword:@"" key:self.key order:self.order price_from:@"" price_to:@""];
            }
                break;
                
            case 3:
            {
                self.layout = layout;
                [self.collectionView reloadData];
            }
                break;
                
            default:
                break;
        }
        
    };
    [self.view addSubview:selectView];
    self.selectView = selectView;
}

- (void)setupCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 50, ScreenWidth, self.view.height-50) collectionViewLayout:flowLayout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
    //注册
    [collectionView registerNib:[UINib nibWithNibName:@"GYStoreAllHorCell" bundle:nil] forCellWithReuseIdentifier:storeAllHorCellIdentifier];
    
    [collectionView registerNib:[UINib nibWithNibName:@"GYStoreAllVerCell" bundle:nil] forCellWithReuseIdentifier:storeAllVerCellIdentifier];
    
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:storeAllHeadView];
    
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

- (void)loadMoreData {
    [self.collectionView.mj_footer endRefreshing];
    [self loadStoreAllGoods:[NSString stringWithFormat:@"%zd",self.currentPage] page:[NSString stringWithFormat:@"%zd",count] stc_id:@"" keyword:@"" key:self.key order:self.order price_from:@"" price_to:@""];
}

- (void)loadStoreAllGoods:(NSString *)curpage page:(NSString *)page stc_id:(NSString *)stc_id keyword:(NSString *)keyword key:(NSString *)key order:(NSString *)order price_from:(NSString *)price_from price_to:(NSString *)price_to {

    if (self.isHasmore) {
        [EasyLodingView showLodingText:@"正在加载..."];
        [GYNetWorkTools requestStoreAllGoods:self.store_id curpage:curpage page:page stc_id:stc_id keyword:keyword key:key order:order price_from:price_from price_to:price_to success:^(NSDictionary *obj) {
            //NSLog(@"obj ========%@",obj);
            int code = [[obj objectForKey:@"code"] intValue];
            NSDictionary *datas = [obj objectForKey:@"datas"];
            if (code == 200) {
                [EasyLodingView hidenLoding];
                self.currentPage += 1;
                //判断是否在次请求的判断标示
                self.hasmore = [[obj objectForKey:@"hasmore"] boolValue];
                
                NSArray *goods_list = [datas objectForKey:@"goods_list"];
                NSArray *models = [GYSearchGoos loadGoodsData:goods_list];
                [self.goodsList addObjectsFromArray:models];
                [self.collectionView reloadData];
            }else if (code == 400) {
                [EasyTextView showText:@"加载数据出错!"];
                [EasyLodingView hidenLoding];
                NSLog(@"网络数据加载失败...");
            }
        } error:^(NSError *error) {
            [EasyTextView showText:@"加载数据出错!"];
            [EasyLodingView hidenLoding];
            NSLog(@"laodStoreAllGoodsFailed====%@",error);
        }];
    }else {
        [EasyTextView showText:@"没有更多数据了!"];
        NSLog(@"没有数据可以加载了.....");
    }
}

#pragma mark -- UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayou

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.goodsList.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.layout) {
        //纵向
        GYStoreAllVerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:storeAllVerCellIdentifier forIndexPath:indexPath];
        cell.model = self.goodsList[indexPath.item];
        
        //判断是否到最底端  判断要加载的数据是按照上面格式排布的数据
//        if (indexPath.row == self.goodsList.count - 1) {
//            [self loadStoreAllGoods:[NSString stringWithFormat:@"%zd",self.currentPage] page:[NSString stringWithFormat:@"%zd",count] stc_id:@"" keyword:@"" key:self.key order:self.order price_from:@"" price_to:@""];
//        }
        
        return cell;
    }else {
        //横向
        GYStoreAllHorCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:storeAllHorCellIdentifier forIndexPath:indexPath];
        cell.model = self.goodsList[indexPath.item];
        
        //判断是否到最底端  判断要加载的数据是按照上面格式排布的数据
//        if (indexPath.row == self.goodsList.count - 1) {
//            [self loadStoreAllGoods:[NSString stringWithFormat:@"%zd",self.currentPage] page:[NSString stringWithFormat:@"%zd",count] stc_id:@"" keyword:@"" key:self.key order:self.order price_from:@"" price_to:@""];
//        }
        
        return cell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    GYSearchGoos *model = self.goodsList[indexPath.item];
    if (self.layout) {
        GYStoreAllVerCell *cell = [[[NSBundle mainBundle]loadNibNamed:@"GYStoreAllVerCell" owner:nil options:nil] firstObject];
        
        return CGSizeMake((ScreenWidth-5)/2, [cell height:model]);
    }else {
        GYStoreAllHorCell *cell = [[[NSBundle mainBundle]loadNibNamed:@"GYStoreAllHorCell" owner:nil options:nil] firstObject];
        
        return CGSizeMake(ScreenWidth, [cell height:model]);
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GYSearchGoos *model = self.goodsList[indexPath.item];
    GYShopHomeViewController *shopHomeVC = [[GYShopHomeViewController alloc] init];
    shopHomeVC.goods_id = model.goods_id;
    [self.navigationController pushViewController:shopHomeVC animated:YES];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:storeAllHeadView forIndexPath:indexPath];
        headView.backgroundColor = [UIColor clearColor];
        UIButton *btu = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, headView.height)];
        [btu setTitle:@"筛选" forState:UIControlStateNormal];
        [btu addTarget:self action:@selector(priceScreen) forControlEvents:UIControlEventTouchUpInside];
        btu.titleLabel.font = [UIFont systemFontOfSize:12];
        [btu setTitleColor:RGBColor(136, 136, 136) forState:UIControlStateNormal];
        [headView addSubview:btu];
        
        return headView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(ScreenWidth, 40);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return self.layout ? 5 : 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return self.layout ? 5 : 0;
}

- (void)priceScreen {
    
    GYPriceScreenViewController *priceScreenVC = [[GYPriceScreenViewController alloc] initWithNibName:@"GYPriceScreenViewController" bundle:nil];
    priceScreenVC.store_id = self.store_id;
    __weak typeof(self) weakSelf = self;
    priceScreenVC.shopPriceScreenCallBack = ^(NSString *minPrice, NSString *maxPrice) {
        [weakSelf.goodsList removeAllObjects];
        weakSelf.currentPage = 1;
        weakSelf.hasmore = YES;
        //根据价格来筛选商品
        [weakSelf loadStoreAllGoods:[NSString stringWithFormat:@"%zd",weakSelf.currentPage] page:[NSString stringWithFormat:@"%zd",count] stc_id:@"" keyword:@"" key:@"" order:@"" price_from:minPrice price_to:maxPrice];
    };
    [self.navigationController pushViewController:priceScreenVC animated:YES];
}

#pragma mark -- 懒加载

- (NSMutableArray *)goodsList {
    if (!_goodsList) {
        _goodsList = [NSMutableArray array];
    }
    
    return _goodsList;
}

@end
